package model

import (
	"encoding/json"
	"hft/tools/ws/single_ws/const_val"
	"hft/tools/ws/single_ws/e"
	"log"

	"github.com/gorilla/websocket"
)

func (manager *ClientManager) MessageChan() {
	for {
		log.Println("管道监听中")
		select {
		case conn := <-Manager.Register: //监听有用户注册
			// 判断是否已经建立链接
			if Manager.Clients[conn.ID] == nil {
				log.Printf("建立新的连接:%v", conn.ID)
				Manager.Clients[conn.ID] = conn //注册
				replyMsg := ReplyMsg{
					Type:    const_val.LinkType,
					Code:    e.WebsocketSuccess,
					Content: "已连接服务器",
				}
				msg, _ := json.Marshal(replyMsg)
				_ = conn.Socket.WriteMessage(websocket.TextMessage, msg)
			}

		case conn := <-Manager.Unregister: //断开连接
			log.Printf("断开连接:%v", conn.ID)
			if _, ok := Manager.Clients[conn.ID]; ok {
				replyMsg := ReplyMsg{
					Type:    const_val.LinkType,
					Code:    e.WebsocketEnd,
					Content: "连接已断开",
				}
				msg, _ := json.Marshal(replyMsg)
				_ = conn.Socket.WriteMessage(websocket.TextMessage, msg)
				close(conn.Send) //关闭管道
				delete(Manager.Clients, conn.ID)
				conn.Socket.Close() //管理连接
			}
			// 广播消息
		case broadcast := <-Manager.Broadcast:
			message := broadcast.Message
			sendId := broadcast.Client.SendID
			flag := false //默认不在线
			for id, conn := range Manager.Clients {
				if id != sendId {
					continue
				}
				select {
				case conn.Send <- message:
					// 发送消息
					flag = true
				default:
					close(conn.Send)
					delete(Manager.Clients, conn.ID)
					conn.Socket.Close()
				}
			}
			if flag {
				log.Println("对方在线应答")
				reply := &ReplyMsg{
					Type:    const_val.StatusType,
					Code:    e.WebsocketOnlineReply,
					Content: "对方在线应答",
				}
				msg, _ := json.Marshal(reply)
				_ = broadcast.Client.Socket.WriteMessage(websocket.TextMessage, msg) //向广播类的当前用户广播消息
			} else {
				log.Println("对方不在线")
				replyMsg := &ReplyMsg{
					Type:    const_val.StatusType,
					Code:    e.WebsocketOfflineReply,
					Content: "对方不在线",
				}
				msg, _ := json.Marshal(replyMsg)
				_ = broadcast.Client.Socket.WriteMessage(websocket.TextMessage, msg)
			}
		}
	}
}
